package org.goldenport.g3.admin

import org.goldenport.g3._
import org.goldenport.g3.atom._
import org.goldenport.g3.messages._
import org.goldenport.g3.messages.datastore.{Create, Fetch, Query, Insert, Update, Delete, Drop}
import org.goldenport.g3.events.RecordFetched

/**
 * @since   Oct. 12, 2010
 * @version Oct. 24, 2010
 * @version Dec.  4, 2011
 * @author  ASAMI, Tomoharu
 */
class G3AuthAdmin extends G3Application with UseRecord {
  datastore('admin,
            RecordClassSpace(
              RecordClass('g3user,
                          Schema(
                            IdField('user, XToken),
                            ('password, XToken),
                            ('memo, XString)))))

  port("/admin/index") html(
<body>
  <ul>
    <li><a g.href="/admin/build">Build</a></li>
    <li><a g.href="/admin/destroy">Build</a></li>
  </ul>
</body>,
    "Auth Admin"
  )

  port("/admin/build") agents(Create('admin)) invoke('admin)
  port("/admin/destroy") agents(Drop('admin)) invoke('admin)

  port("/login") agent {
    case get: Get => {
      val record = get.asRecord
      val username = record('username)
      val password = record('password)
      Fetch('admin, username).properties('password -> password)
    }
  } invoke('admin) agent {
    case fetched: RecordFetched => {
      val record = fetched.asRecord
      val datapassword = record('password)
      val inpassword = fetched.property('password)
      if (datapassword == inpassword) G3User(record)
      else None
    }
  }

  port("/newaccount") agent {
    case post: Post => {
      val in = post.asRecord
      val out = Record(
        'user -> in('username),
        'password -> in('password))
      out
    }
  } invoke('admin)

  port("/updateaccount") agent {
    case post: Post => {
      val in = post.asRecord
      val out = Record(
        'user -> in('username),
        'password -> in('password))
      out
    }
  } invoke('admin)

  port("/view/login") html(
<body>
  <g.login/>
</body>
  , "Login")

  port("/view/newaccount") html(
<body>
  <g.input action="/newaccount"/>
</body>,
    "Create Account",
    Schema(
      IdField('user, XToken),
      Field('password, XToken, MOne, List(CPassword)),
      Field('password2, XToken, MOne, List(CPassword))))

  port("/view/updateaccount") html(
<body>
  <g.input update="true" action="/updateaccount"/>
</body>,
    "User Account",
    Schema(
      IdField('user, XToken),
      ('twitter, XToken)))
}
